import { LockOutlined, MobileOutlined, RollbackOutlined, UserOutlined } from '@ant-design/icons';
import { Alert, Col, message, Row, Tabs, Image, Button } from 'antd';
import React, { useEffect, useState } from 'react';
import { ProFormCaptcha, ProFormCheckbox, ProFormText, LoginFormPage } from '@ant-design/pro-form';
// @ts-ignore
import { useIntl, history, FormattedMessage, SelectLang, useModel, Link } from 'umi';

import styles from './index.less';
import { clearSessionToken, setSessionToken } from '@/access';
import { loginUsingPOST } from '@/services/ctb-service/login';
import { captchaGetImageUsingGET } from '@/services/ctb-service/captcha';
import request from '@/utils/request';
import {getUserInfo, logout} from '@/services';

const LoginMessage: React.FC<{
  content: string;
}> = ({ content }) => (
  <Alert
    style={{
      marginBottom: 24,
    }}
    message={content}
    type="error"
    showIcon
  />
);

const Login: React.FC = () => {
  const [userLoginState, setUserLoginState] = useState<any>({});
  const [type, setType] = useState<string>('account');
  const { initialState, setInitialState } = useModel('@@initialState');

  const [captchaCode, setCaptchaCode] = useState<string>('');
  const [uuid, setUuid] = useState<string>('');

  const intl = useIntl();

  const items = [{ label: '账户密码登录', key: 'account', id: 'pages.login.accountLogin.tab' }];

  // 根据后端配置判断是否显示验证码
  const [showCaptcha, setShowCaptcha] = useState<any>(false);

  const fetchUserInfo = async () => {
    const userInfo = await initialState?.fetchUserInfo?.();
    if (userInfo) {
      await setInitialState((s: any) => ({
        ...s,
        currentUser: userInfo,
      }));
    }
  };

  const checkBeforeGoBack = async () => {
    // 回到首页存在以下情况
    // 1. 匿名用户回到首页
    // 2. 已登录用户回到首页
    // 3. 已登录用户退出登录后回到首页
    // 针对第三种情况，需要回到首页之后登陆匿名用户
    const resp = await getUserInfo();
    await setInitialState((s: any) => ({
      ...s,
      currentUser: { ...resp.user, permissions: resp.permissions },
    }));
    history.push('/');
  };

  // 如果用户已登录跳转首页，防止已登录的用户二次登陆，否则一个用户不停的登陆会在后台生成多个token
  const checkIsLoginAndRedirect = async () => {
    const resp = await request<API.GetUserInfoResult>('/api/getInfo', {
      method: 'GET',
    });
    if (resp.code === 200 && resp.user?.userName !== 'anon') {
      console.log(resp);
      const defaultLoginSuccessMessage = intl.formatMessage({
        id: 'pages.login.already.login',
        defaultMessage: '检测到您已登录，正在跳转！',
      });
      message.success(defaultLoginSuccessMessage);
      // 如果用户已经登陆，要填充用户信息，否则会出现用户信息为空的情况，首页没有数据
      await setInitialState((s: any) => ({
        ...s,
        currentUser: { ...resp.user, permissions: resp.permissions } as API.CurrentUser,
      }));
      if (!history) return;
      const { query } = history.location;
      const { redirect } = query as { redirect: string };
      history.push(redirect || '/');
    } else {
      return;
    }
  };

  const getCaptchaCode = async () => {
    const response = await captchaGetImageUsingGET();
    const imgdata = `data:image/png;base64,${response.img}`;
    setShowCaptcha(response.captchaEnabled);
    setCaptchaCode(imgdata);
    setUuid(response.uuid);
  };

  const handleSubmit = async (values: API.LoginParams) => {
    try {
      if (values.rememberMe) {
        localStorage.setItem('username', values.username || '');
        localStorage.setItem('password', values.password || '');
      } else {
        localStorage.removeItem('username');
        localStorage.removeItem('password');
      }
      // 登录前先试试登出
      await logout();
      const response = await loginUsingPOST({ ...values, uuid });
      if (response.code === 200) {
        const defaultLoginSuccessMessage = intl.formatMessage({
          id: 'pages.login.success',
          defaultMessage: '登录成功！',
        });
        const current = new Date();
        const expireTime = current.setTime(current.getTime() + 1000 * 12 * 60 * 60);
        setSessionToken(response.token, response.token, expireTime);
        message.success(defaultLoginSuccessMessage);

        await fetchUserInfo();
        /** 此方法会跳转到 redirect 参数所在的位置 */
        if (!history) return;

        const { query } = history.location;
        const { redirect } = query as { redirect: string };
        history.push(redirect || '/');
        return;
      } else {
        clearSessionToken();
        // 如果失败去设置用户错误信息
        setUserLoginState({ status: 'error', type: 'account', massage: response.msg });
        message.error(response.msg);
        getCaptchaCode();
      }
    } catch (error) {
      clearSessionToken();
      const defaultLoginFailureMessage = intl.formatMessage({
        id: 'pages.login.failure',
        defaultMessage: '登录失败，请重试！',
      });
      message.error(defaultLoginFailureMessage);
      getCaptchaCode();
    }
  };
  const { status, type: loginType, massage } = userLoginState;

  useEffect(() => {
    checkIsLoginAndRedirect();
    getCaptchaCode();
  }, []);

  return (
    <div className={styles.container}>
      <div className={styles.lang} data-lang="">
        {SelectLang && <SelectLang />}
      </div>
      <div className={styles.content}>
        <LoginFormPage
          backgroundImageUrl="https://tremblingoss.oss-cn-shanghai.aliyuncs.com/ctb/face-box.svg"
          // logo={<img alt="logo" src="/logo.svg" />}
          title="Common Tool Box"
          subTitle={intl.formatMessage({ id: 'pages.layouts.userLayout.title' })}
          initialValues={{
            // userName: localStorage.getItem('username') || '',
            // password: localStorage.getItem('password') || '',
            rememberMe: true,
          }}
          // actions={[
          //   <FormattedMessage
          //     key="loginWith"
          //     id="pages.login.loginWith"
          //     defaultMessage="其他登录方式"
          //   />,
          //   <AlipayCircleOutlined key="AlipayCircleOutlined" className={styles.icon}/>,
          //   <TaobaoCircleOutlined key="TaobaoCircleOutlined" className={styles.icon}/>,
          //   <WeiboCircleOutlined key="WeiboCircleOutlined" className={styles.icon}/>,
          // ]}
          onFinish={async (values) => {
            await handleSubmit(values as API.LoginParams);
          }}
          activityConfig={{
            action: (
              <Button
                icon={<RollbackOutlined />}
                type="text"
                size="large"
                style={{
                  borderRadius: 20,
                  background: 'rgba(0,0,0,0)',
                  color: 'black',
                  fontSize: 14,
                  fontWeight: 'bolder',
                }}
                onClick={checkBeforeGoBack}
              >
                不想登录啦？回到首页！
              </Button>
            ),
          }}
        >
          <Tabs activeKey={type} onChange={setType} items={items}></Tabs>

          {status === 'error' && loginType === 'account' && <LoginMessage content={massage} />}
          {type === 'account' && (
            <>
              <ProFormText
                name="username"
                fieldProps={{
                  size: 'large',
                  prefix: <UserOutlined className={styles.prefixIcon} />,
                }}
                placeholder={intl.formatMessage({
                  id: 'pages.login.username.placeholder',
                  defaultMessage: '用户名',
                })}
                rules={[
                  {
                    required: true,
                    message: (
                      <FormattedMessage
                        id="pages.login.username.required"
                        defaultMessage="请输入用户名!"
                      />
                    ),
                  },
                ]}
              />
              <ProFormText.Password
                name="password"
                fieldProps={{
                  size: 'large',
                  prefix: <LockOutlined className={styles.prefixIcon} />,
                }}
                placeholder={intl.formatMessage({
                  id: 'pages.login.password.placeholder',
                  defaultMessage: '密码',
                })}
                rules={[
                  {
                    required: true,
                    message: (
                      <FormattedMessage
                        id="pages.login.password.required"
                        defaultMessage="请输入密码！"
                      />
                    ),
                  },
                ]}
              />
              {/*先判断一下后端是不是关闭了验证码*/}
              {showCaptcha && (
                <Row>
                  <Col flex={3}>
                    <ProFormText
                      style={{
                        float: 'right',
                      }}
                      name="code"
                      placeholder={intl.formatMessage({
                        id: 'pages.login.code.placeholder',
                        defaultMessage: '请输入验证',
                      })}
                      rules={[
                        {
                          required: true,
                          message: (
                            <FormattedMessage
                              id="pages.searchTable.updateForm.ruleName.nameRules"
                              defaultMessage="请输入验证码！"
                            />
                          ),
                        },
                      ]}
                    />
                  </Col>
                  <Col flex={2}>
                    <Image
                      src={captchaCode}
                      alt="验证码"
                      style={{
                        display: 'inline-block',
                        verticalAlign: 'top',
                        cursor: 'pointer',
                        paddingLeft: '10px',
                        width: '100px',
                      }}
                      preview={false}
                      onClick={() => getCaptchaCode()}
                    />
                  </Col>
                </Row>
              )}
            </>
          )}

          {status === 'error' && loginType === 'mobile' && <LoginMessage content="验证码错误" />}
          {type === 'mobile' && (
            <>
              <ProFormText
                fieldProps={{
                  size: 'large',
                  prefix: <MobileOutlined className={styles.prefixIcon} />,
                }}
                name="mobile"
                placeholder={intl.formatMessage({
                  id: 'pages.login.phoneNumber.placeholder',
                  defaultMessage: '手机号',
                })}
                rules={[
                  {
                    required: true,
                    message: (
                      <FormattedMessage
                        id="pages.login.phoneNumber.required"
                        defaultMessage="请输入手机号！"
                      />
                    ),
                  },
                  {
                    pattern: /^1\d{10}$/,
                    message: (
                      <FormattedMessage
                        id="pages.login.phoneNumber.invalid"
                        defaultMessage="手机号格式错误！"
                      />
                    ),
                  },
                ]}
              />
              <ProFormCaptcha
                fieldProps={{
                  size: 'large',
                  prefix: <LockOutlined className={styles.prefixIcon} />,
                }}
                captchaProps={{
                  size: 'large',
                }}
                placeholder={intl.formatMessage({
                  id: 'pages.login.captcha.placeholder',
                  defaultMessage: '请输入验证码',
                })}
                captchaTextRender={(timing, count) => {
                  if (timing) {
                    return `${count} ${intl.formatMessage({
                      id: 'pages.getCaptchaSecondText',
                      defaultMessage: '获取验证码',
                    })}`;
                  }
                  return intl.formatMessage({
                    id: 'pages.login.phoneLogin.getVerificationCode',
                    defaultMessage: '获取验证码',
                  });
                }}
                name="captcha"
                rules={[
                  {
                    required: true,
                    message: (
                      <FormattedMessage
                        id="pages.login.captcha.required"
                        defaultMessage="请输入验证码！"
                      />
                    ),
                  },
                ]}
                onGetCaptcha={async (phone) => {
                  // const result = await getFakeCaptcha({
                  //   phone,
                  // });
                  // if (result === false) {
                  //   return;
                  // }
                  message.success('获取验证码成功！验证码为：1234');
                }}
              />
            </>
          )}
          <div
            style={{
              marginBottom: 24,
            }}
          >
            <ProFormCheckbox noStyle name="rememberMe">
              <FormattedMessage id="pages.login.rememberMe" defaultMessage="记住密码" />
            </ProFormCheckbox>
            {/*<a*/}
            {/*  style={{*/}
            {/*    float: 'right',*/}
            {/*  }}*/}
            {/*>*/}
            {/*  <FormattedMessage id="pages.login.forgotPassword" defaultMessage="忘记密码"/>*/}
            {/*</a>*/}
          </div>
        </LoginFormPage>
      </div>
      {/*<Footer />*/}
    </div>
  );
};

export default Login;
